package jdbc3;

/**
 * @Auther:lele
 * @Date:2025/3/12
 */
import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author 路老师
 * @date 2025/3/12
 * 无精神，不编程！无乐趣，不编程！
 * “调试：与bug共舞的艺术。”
 */
public class userStransction {
    @Test
    //事务来解决
    public void useTransaction() throws SQLException {
// 1. 得到连接
        Connection connection = null;
//2. 组织一个 sql
        String sql = "update user set money = money-10 where admin='张三'";
        String sql2 = "update user set money = money+10  where admin='李四'";
        PreparedStatement preparedStatement = null;
//3. 创建 PreparedStatement 对象
        try {
            String url = "jdbc:mysql://localhost:3306/ma?useSSL=false&serverTimezone=UTC";
            String username = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, username, password);
//将 connection 设置为不自动提交
//            connection.setAutoCommit(false); //开启了事务
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate(); // 执行第1 条sql

            int i = 1 / 0; //抛出异常

            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate(); // 执行第3 条sql//这里提交事务

            connection.commit();
        } catch (SQLException e) { //这里我们可以进行回滚，即撤销执行的 SQL
// 默认回滚到事务开始的状态.
//            System.out.println("执行发生了异常，撤销执行的sql");
//            try {
//                connection.rollback();
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }
//            e.printStackTrace();
        }finally {
            //关闭资源
            preparedStatement.close();
            connection.close();
        }
    }
}
